package com.qiguliuxing.dts.service.seckill.model;

import java.util.ArrayList;
import java.util.List;

public class ShapeLinkList<E> {
    public Node<E> first;

    public Node<E> head;

    public int theSize;

    public ShapeLinkList() {
        ininLinkList();
    }

    public boolean ininLinkList() {
        theSize = 0;
        first = new Node<>(null,null);
        head = new Node<>(null,first);
        first.next = head;
        return true;
    }

    public Node<E> getNode(int i){
       Node<E> reNode = head;
       for (int j =-2;j<i;j++) {
           reNode = reNode.next;
       }
       return reNode;
    }

    public void add(E data) {
        Node newNode = new Node<>(data,null);
        getNode(theSize-1).next = newNode;
        newNode.next = first.next;
        theSize++;
    }

    public void add(int i,E data) {
        Node preNode = getNode(i-1);
        Node newNode = new Node<>(data,preNode.next);
        preNode.next = newNode;
        theSize++;
    }

    public boolean isEmpty() {
        return theSize == 0;
    }

    public E remove(int i) {
        if (i == theSize - 1) {
            E a = getNode(theSize - 1).data;
            getNode(theSize - 2).next = first.next;
            return a;
        }
        Node<E> prev = getNode(theSize - 1);
        E a = prev.next.data;
        prev.next = prev.next.next;
        theSize --;
        return  a;
    }

    public E get(int i) {
        return getNode(i).data;
    }

    public List<E> get(int index, int count) {
        int currentIndex = index - 1;
        List<E> resData = new ArrayList<E>();
        E currData = getNode(currentIndex).data;
        resData.add(currData);
        for (int j = 1; j < count; j ++) {
            E indexData = getNode(currentIndex + j).data;
            resData.add(indexData);
        }
        return resData;
    }

    public void set(int index, E data) {
        getNode(index).data = data;
    }

    public void clear() {
        ininLinkList();
    }

    public int length(){
        return  theSize;
    }

    public void print(){
        for (int i =0; i<theSize; i++) {
            System.out.println(getNode(i).data);
        }
    }

    public class Node<E>{
      public E data;
      public Node<E> next;

      public Node(E data,Node<E> next){
        this.data = data;
        this.next = next;
      }
    }
}
